<template>
  <div
    class="duyi-collapse-item"
    :class="{
      'is-disabled': disabled,
    }"
  >
    <!-- 标题部分 -->
    <div
      class="duyi-collapse-item__header"
      :class="{
        'is-disabled': disabled,
        'is-active': isActive,
      }"
      :id="`item-header-${name}`"
      @click="itemClickHandle"
    >
      <slot name="title">{{ title }}</slot>
      <Duyi-Icon icon="angle-right" class="header-angle" />
    </div>
    <!-- 内容部分 -->
    <Transition name="slide" v-on="transitionEvents">
      <div class="duyi-collapse-item__wrapper" v-show="isActive">
        <div class="duyi-collapse-item__content" :id="`item-content-${title}`">
          <slot></slot>
        </div>
      </div>
    </Transition>
  </div>
</template>

<script setup>
import { computed, inject } from 'vue'
import { collapseItemProps, collapseCountextKey } from '../props.js'
defineOptions({
  name: 'DuyiCollapseItem',
})
const props = defineProps(collapseItemProps)

// 通过 inject 可以拿到 Collapse 组件提供的方法和属性
const collapseContext = inject(collapseCountextKey)

// 是否是激活状态
const isActive = computed(() =>
  collapseContext.activeNames.value.includes(props.name),
)

// 点击事件处理函数
const itemClickHandle = () => {
  if (props.disabled) return
  // 这里就触发 Collapse 组件提供的方法
  collapseContext.handleItemClick(props.name)
}

// 在这个对象里面，会指定过渡开始和结束时的不同样式
const transitionEvents = {
  beforeEnter(el) {
    el.style.height = '0px'
    el.style.overflow = 'hidden'
  },
  enter(el) {
    el.style.height = el.scrollHeight + 'px'
  },
  afterEnter(el) {
    el.style.height = ''
    el.style.overflow = ''
  },
  beforeLeave(el) {
    el.style.height = el.scrollHeight + 'px'
    el.style.overflow = 'hidden'
  },
  leave(el) {
    el.style.height = '0px'
  },
  afterLeave(el) {
    el.style.height = ''
    el.style.overflow = ''
  },
}
</script>

<style lang="scss" scoped></style>
